<template>
    <div id="WindowsContingencyPlanOperation">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px" class="demo-ruleForm"
            :size="formSize" status-icon style="background-color: var(--el-fill-color-blank);padding: 10px 0;">
            <div
                style="position: absolute;top:0;width: 100%;z-index: 100;background-color: var(--el-fill-color-blank);padding: 10px 0;">
                <div style="display: flex; justify-content: space-between; align-items: center; position: relative;">
                    <el-page-header @back="goBack" title="返回" style="margin-left: 10px;">
                        <template #content>
                            <div>
                                <span class="text-large font-600 mr-3"> {{ title }} </span>
                            </div>
                        </template>
                    </el-page-header>

                    <el-button type="primary" v-if="!isDisable" @click="submitForm(ruleFormRef)" style="margin-right: 10px;">
                        {{ btnText }}
                    </el-button>
                </div>
                <el-divider style="margin: 10px 0 0 0 ;" />
            </div>
            <div style="padding: 10px;">
                <el-form-item label="方案标题：" prop="title" style="margin-top:70px ;">
                    <el-input v-model="ruleForm.title" :disabled="isDisable" />
                </el-form-item>
                <el-form-item label="方案说明：" prop="explain">
                    <el-input v-model="ruleForm.explain" type="textarea" :disabled="isDisable"/>
                </el-form-item>
                <el-form-item label="发布时间：" prop="createTime" v-if="isType">
                    <el-date-picker v-model="ruleForm.createTime" type="datetime" disabled />
                </el-form-item>
                <el-form-item :label="transferTitle+'清单：'" prop="leaderUsers">
                    <el-transfer v-model="ruleForm.leaderUsers" style="text-align: left; display: inline-block" filterable
                        :titles="['所有人员', transferTitle]" :button-texts="['取消', '添加']" :data="data" @change="handleChange">
                    </el-transfer>
                </el-form-item>
                <el-form-item label="方案内容：" prop="detail" style="margin-bottom: 0;">
                </el-form-item>
                <div style="display: block ;padding-left: 50px ;margin-top: 20px;">
                    <div style="border: 1px solid var(--el-border-color);border-radius: 0;">
                        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig"
                            :mode="mode" />
                        <Editor style="min-height: 200px; overflow-y: hidden;" v-model="ruleForm.detail"
                            :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
                    </div>
                </div>
            </div>
        </el-form>

    </div>
</template>

<script setup >

import { useRouter, useRoute } from 'vue-router';

import '@wangeditor/editor/dist/css/style.css' // 引入 css

import { onBeforeUnmount, ref, reactive, shallowRef, inject } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import axios from '@/utils/axios'
import { ElLoading, ElMessageBox } from 'element-plus';
import dateTimeSpan from '@/utils/dateTime';
import { dateTimeSpanWebApi } from '@/utils/dateTime';

var title = ref("新增应急方案");
const router = useRouter();
const route = useRoute();
const ContingencyPlanNo = route.query.ContingencyPlanNo;
const Type = route.query.Type;
const HistoryId = route.query.HistoryId;
const transferTitle = ref('默认负责人')

const goBack = () => {
    router.back();
}
const isType = ref(false);
const isDisable = ref(false);
var btnText = ref("确认添加");

if (ContingencyPlanNo != null && Type != null) {
    if (Type == 1) {
        btnText.value = "确认修改";
        title.value = "修改应急方案";
    } else if (Type == 2) {
        btnText.value = "确认发布";
        title.value = "发布应急方案";
        isType.value = true;
    }
}

if (HistoryId != null && Type != null) {
    if (Type == 3) {
        isDisable.value = true;
        title.value = "查看应急方案";
        transferTitle.value = '负责人';
    }
}
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const mode = ref('default')

const toolbarConfig = ref({})
toolbarConfig.value.excludeKeys = [
    'emotion',
]

const editorConfig = ref({
    placeholder: '请输入内容...', MENU_CONF: {}
})
editorConfig.value.MENU_CONF['uploadImage'] = {
    server: '/api/EditorUpImage',
    headers: {
        "X-Token": getToken()
    },
}
editorConfig.value.MENU_CONF['uploadVideo'] = {
    server: '/api/EditorUpImage',
    headers: {
        "X-Token": getToken()
    },
}
editorConfig.value.scroll = false
editorConfig.value.autoFocus = false

editorConfig.value.readOnly = isDisable.value
let RYD_UserId = inject('RYD_UserId');

function getToken() {
    try {
        var token = sessionStorage.getItem('token');
        if (sessionStorage.getItem('RYD_UserId') != null) {
            token += ";" + sessionStorage.getItem('RYD_UserId')
        }
        return token;
    } catch (error) {
        return null;
    }
}
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
};


const formSize = ref('large')
const ruleFormRef = ref()
const ruleForm = reactive({
    title: '',
    explain: '',
    leaderUsers: [],
    detail: '',
    createTime: dateTimeSpan(Date.now())
})

const validatePass = (rule, value, callback) => {
    if (value === '<p><br></p>') {
        callback('请填写方案内容')
    } else {
        callback()
    }
}

const rules = reactive({
    title: [
        { required: true, message: '请填写方案标题', trigger: 'blur' },
    ],
    explain: [
        { required: true, message: '请填写方案说明', trigger: 'blur' },
    ],
    detail: [
        { required: true, message: '请填写方案内容', trigger: 'blur' },
        { validator: validatePass, trigger: 'blur' },
    ],
})

const submitForm = async (formEl) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {

            const loading = ElLoading.service({
                lock: true,
                text: '提交中',
                background: 'rgba(0, 0, 0, 0.7)',
            })

            var leaderUsers = '';
            ruleForm.leaderUsers.forEach(item => {
                if (leaderUsers != '') {
                    leaderUsers += ",";
                }
                leaderUsers += item;
            });

            if (ContingencyPlanNo != null && Type != null) {
                //发布
                if (Type == 2) {
                    axios({
                        method: 'post',
                        url: '/api/PublishContingencyPlanTable',
                        data: {
                            RYD_ContingencyPlanTitle: ruleForm.title,
                            RYD_ContingencyPlanExplain: ruleForm.explain,
                            RYD_ContingencyPlanDetail: ruleForm.detail,
                            RYD_LeaderUsers: leaderUsers,
                            RYD_CreateBy: RYD_UserId,
                            RYD_CreateTime: dateTimeSpanWebApi(ruleForm.createTime),
                            RYD_ContingencyPlanNo: ContingencyPlanNo
                        }
                    }).then(() => {
                        loading.close();
                        ElMessageBox.alert('发布成功，已通知负责人', '提示');
                    }).catch(err => {
                        loading.close();
                        ElMessageBox.alert('失败:' + err, '提示');
                    })
                    return;
                }
                //修改
                else if (Type == 1) {
                    axios({
                        method: 'post',
                        url: '/api/AddContingencyPlanTable',
                        data: {
                            RYD_ContingencyPlanTitle: ruleForm.title,
                            RYD_ContingencyPlanExplain: ruleForm.explain,
                            RYD_ContingencyPlanDetail: ruleForm.detail,
                            RYD_DefaultUsers: leaderUsers,
                            RYD_CreateBy: RYD_UserId,
                            RYD_ContingencyPlanNo: ContingencyPlanNo
                        }
                    }).then(() => {
                        loading.close();
                        ElMessageBox.alert('修改成功', '提示');
                    }).catch(err => {
                        loading.close();
                        ElMessageBox.alert('失败:' + err, '提示');
                    })
                    return;
                }
            }
            axios({
                method: 'post',
                url: '/api/AddContingencyPlanTable',
                data: {
                    RYD_ContingencyPlanTitle: ruleForm.title,
                    RYD_ContingencyPlanExplain: ruleForm.explain,
                    RYD_ContingencyPlanDetail: ruleForm.detail,
                    RYD_DefaultUsers: leaderUsers,
                    RYD_CreateBy: RYD_UserId,
                }
            }).then(() => {
                loading.close();
                ElMessageBox.alert('添加成功', '提示');
                ruleForm.title = '';
                ruleForm.explain = '';
                ruleForm.leaderUsers = [];
                ruleForm.detail = '';
            }).catch(err => {
                loading.close();
                ElMessageBox.alert('失败:' + err, '提示');
            })
        } else {
            console.log('error submit!', fields)
        }
    })
}
axios({
    method: 'post',
    url: '/api/GetAllUser',
    data: {

    }
}).then(res => {
    res.forEach(item => {
        data.value.push({
            key: item.ryD_Id,
            label: item.ryD_RyderNo + " " + item.realName
        })
    });
})

const data = ref([])

const handleChange = () => {
    if(HistoryId != null && Type != null){
        ruleForm.leaderUsers = lduser;
    }
}


if (ContingencyPlanNo != null) {
    axios({
        method: 'get',
        url: '/api/GetContingencyPlanTableInfo?ContingencyPlanNo=' + ContingencyPlanNo,
    }).then(res => {
        ruleForm.detail = res.ryD_ContingencyPlanDetail;
        ruleForm.explain = res.ryD_ContingencyPlanExplain;
        ruleForm.title = res.ryD_ContingencyPlanTitle;
        ruleForm.leaderUsers = res.ryD_DefaultUsers.split(',');
    })
}
var lduser = [];
if (HistoryId != null) {
    axios({
        method: 'get',
        url: '/api/GetContingencyPlanTableHistoryInfo?HistoryId=' + HistoryId,
    }).then(res => {
        ruleForm.detail = res.ryD_ContingencyPlanDetail;
        ruleForm.explain = res.ryD_ContingencyPlanExplain;
        ruleForm.title = res.ryD_ContingencyPlanTitle;
        ruleForm.leaderUsers = res.ryD_LeaderUsers.split(',');
        lduser=res.ryD_LeaderUsers.split(',');
    })
}

</script>

<style>
#WindowsContingencyPlanOperation .el-page-header__breadcrumb {
    margin: 0;
}

#WindowsContingencyPlanOperation h1 {
    font-size: 2rem;
}
</style>